<template>
	<base-layout simple>
		<article class="base-layout__inner column">
			<!-- 查询条件 -->
			<t-form
				ref="form"
				:data="queryParams"
				label-width="80px"
				layout="inline"
				class="search-form"
				colon
			>
				<t-row style="width: 100%">
					<t-col :span="3">
						<t-form-item label="角色名称">
							<t-input
								v-model="queryParams.name"
								placeholder="请输入角色名称"
								clearable
								style="width: 158px"
							/>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item label="角色值">
							<t-input
								v-model="queryParams.value"
								placeholder="请输入角色值"
								clearable
								style="width: 158px"
							/>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item label="状态">
							<t-select
								v-model="queryParams.status"
								placeholder="请选择状态"
								clearable
								style="width: 158px"
							>
								<t-option :value="1" label="启用" />
								<t-option :value="0" label="禁用" />
							</t-select>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item>
							<t-space>
								<t-button theme="primary" @click="handleSearch">查询</t-button>
								<t-button theme="default" @click="handleReset">重置</t-button>
							</t-space>
						</t-form-item>
					</t-col>
				</t-row>

				<t-row style="width: 100%">
					<t-col :span="3">
						<t-row>
							<t-space>
								<t-button theme="primary" @click="handleAdd">新增角色</t-button>
							</t-space>
						</t-row>
					</t-col>
					<t-col :span="9"></t-col>
				</t-row>
			</t-form>

			<!-- 数据表格 -->
			<t-table
				ref="table"
				:data="roleData"
				:columns="columns"
				:loading="loading"
				:pagination="pagination"
				@page-change="handlePageChange"
				@page-size-change="handlePageSizeChange"
				row-key="id"
				bordered
				size="small"
				stripe
			/>
		</article>

		<!-- 角色编辑抽屉 -->
		<role-form-drawer
			:visible.sync="editorVisible"
			:is-edit="isEdit"
			:current-edit-data="currentEditData"
			@save="handleSave"
			@close="handleCloseEditor"
			ref="roleFormDrawer"
		/>
	</base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import RoleFormDrawer from './RoleFormDrawer.vue';
import {
	Button as TButton,
	Tag as TTag,
	Table as TTable,
	Popconfirm as TPopconfirm
} from 'tdesign-vue';
import { getRoleList, createRole, updateRole, deleteRole, getRoleById } from '@/api/role';

export default {
	name: 'SystemRole',
	components: {
		BaseLayout,
		RoleFormDrawer,
		TTable,
		TButton
	},
	data() {
		return {
			loading: false,
			editLoading: false,
			editorVisible: false,
			currentEditData: null,
			isEdit: false,

			// 查询参数
			queryParams: {
				name: '',
				value: '',
				status: '',
			},

			// 分页参数
			pagination: {
				current: 1,
				pageSize: 10,
				total: 0,
				showJumper: true,
				showSizer: true,
			},

			// 表格列配置
			columns: [
				{
					colKey: 'name',
					title: '角色名称',
					width: 150,
					ellipsis: true,
				},
				{
					colKey: 'value',
					title: '角色值',
					width: 150,
					ellipsis: true,
				},
				{
					colKey: 'status',
					title: '状态',
					width: 100,
					align: 'center',
					cell: (h, { row }) => {
						return h(
							TTag,
							{
								props: {
									theme: row.status === 1 ? 'success' : 'danger',
									size: 'small',
									variant: 'light',
								},
							},
							row.status === 1 ? '启用' : '禁用'
						);
					},
				},
				{
					colKey: 'remark',
					title: '备注',
					width: 200,
					ellipsis: true,
					cell: (h, { row }) => {
						return row.remark || '-';
					},
				},
				{
					colKey: 'createdAt',
					title: '创建时间',
					width: 180,
					ellipsis: true,
				},
				{
					colKey: 'operate',
					title: '操作',
					width: 140,
					fixed: 'right',
					cell: (h, { row }) => {
						return h('div', { class: 'table-operations' }, [
							h(
								'TButton',
								{
									props: {
										variant: 'text',
										theme: 'primary',
										size: 'small',
									},
									on: {
										click: () => this.handleEdit(row),
									},
								},
								'编辑'
							),
							h(
								TPopconfirm,
								{
									props: {
										content: '确认删除吗？删除后不可恢复！',
									},
									on: {
										confirm: () => this.handleDelete(row),
									},
								},
								[
									h(
										'TButton',
										{
											props: {
												variant: 'text',
												theme: 'danger',
												size: 'small',
											},
										},
										'删除'
									),
								]
							),
						]);
					},
				},
			],

			// 角色数据
			roleData: [],
		};
	},

	mounted() {
		this.getRoleList();
	},

	methods: {
		// 获取角色列表
		async getRoleList() {
			this.loading = true;
			try {
				// 构建查询参数，过滤掉空值
				const queryData = {};
				if (this.queryParams.name && this.queryParams.name.trim()) {
					queryData.name = this.queryParams.name.trim();
				}
				if (this.queryParams.value && this.queryParams.value.trim()) {
					queryData.value = this.queryParams.value.trim();
				}
				if (this.queryParams.status !== '' && this.queryParams.status !== null && this.queryParams.status !== undefined) {
					queryData.status = this.queryParams.status;
				}

				const params = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
					...queryData
				};

				const response = await getRoleList(params);
				console.log(response)

				// 假设后端返回格式为: { code: 200, data: { records: [], total: 0 }, message: 'success' }
				if (response?.data?.code === 200) {
					this.roleData = response?.data?.data?.items || [];
					this.pagination.total = response?.data?.data?.meta?.totalItems || 0;
				} else {
					throw new Error(response?.data?.message ?? '获取角色列表失败');
				}
			} catch (error) {
				console.error('获取角色列表失败:', error);
				this.$message.error('获取角色列表失败');
				this.roleData = [];
				this.pagination.total = 0;
			} finally {
				this.loading = false;
			}
		},

		// 查询
		handleSearch() {
			this.pagination.current = 1;
			this.getRoleList();
		},

		// 重置查询条件
		handleReset() {
			this.queryParams = {
				name: '',
				value: '',
				status: '',
			};
			this.pagination.current = 1;
			this.getRoleList();
		},

		// 分页改变
		handlePageChange(pageInfo) {
			this.pagination.current = pageInfo.current;
			this.getRoleList();
		},

		// 分页大小改变
		handlePageSizeChange(pageInfo) {
			this.pagination.pageSize = pageInfo.pageSize;
			this.pagination.current = 1;
			this.getRoleList();
		},

		// 新增角色
		handleAdd() {
			this.isEdit = false;
			this.currentEditData = null;
			this.editorVisible = true;
		},

				// 编辑角色
		async handleEdit(row) {
			if (this.editLoading) return; // 防止重复点击

			try {
				this.editLoading = true;
				this.isEdit = true;

				// 调用详情接口获取最新数据
				const response = await getRoleById(row.id);

				if (response?.data?.code === 200) {
					this.currentEditData = response.data.data;
					this.editorVisible = true;
				} else {
					throw new Error(response?.data?.message ?? '获取角色详情失败');
				}
			} catch (error) {
				console.error('获取角色详情失败:', error);
				this.$message.error('获取角色详情失败');
			} finally {
				this.editLoading = false;
			}
		},

		// 保存角色
		async handleSave(formData) {
			try {
				// 设置抽屉的保存loading状态
				this.$refs.roleFormDrawer.setSaveLoading(true);

				let response;
				if (this.isEdit) {
					// 更新角色
					response = await updateRole(this.currentEditData.id, formData);
					if (response?.data?.code === 200) {
						this.$message.success('角色更新成功');
					} else {
						throw new Error(response?.data?.message ?? '角色更新失败');
					}
				} else {
					// 创建角色
					response = await createRole(formData);
					if (response?.data?.code === 200) {
						this.$message.success('角色创建成功');
					} else {
						throw new Error(response?.data?.message ?? '角色创建失败');
					}
				}

				this.editorVisible = false;
				this.getRoleList();
			} catch (error) {
				console.error('保存角色失败:', error);
				this.$message.error('保存角色失败');
			} finally {
				this.$refs.roleFormDrawer.setSaveLoading(false);
			}
		},

				// 删除角色
		async handleDelete(row) {
			try {
				const response = await deleteRole(row.id);

				if (response?.data?.code === 200) {
					this.$message.success('角色删除成功');
					this.getRoleList();
				} else {
					throw new Error(response?.data?.message ?? '角色删除失败');
				}
			} catch (error) {
				console.error('删除角色失败:', error);
				this.$message.error('删除角色失败');
			}
		},

		// 关闭编辑器
		handleCloseEditor() {
			this.editorVisible = false;
			this.currentEditData = null;
		},
	},
};
</script>

<style lang="less" scoped>
.search-form {
	background: #fff;
}

/deep/ .table-operations {
	.t-button {
		margin-right: 8px;
	}
}

/deep/ .t-table {
	.t-table__header {
		background-color: #f5f7fa;
	}
}
</style>